package com.cn.pool;

import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;

/*
 * 线程管理者
 */
public class NioSelectorRunnablePool {

	/*
	 * boss线程数组
	 */
	private final AtomicInteger bossInteger = new AtomicInteger();
	private Boss[] bosses;
	
	/*
	 * worker线程数组
	 */
	private final AtomicInteger wokerInteger  = new AtomicInteger();
	private Worker[] workers;

	public NioSelectorRunnablePool(Executor boss,Executor worker){
		initBoss(boss, 1);
		initWorker(worker, Runtime.getRuntime().availableProcessors()*2);
		System.out.println("java 虚拟机处理器数量："+Runtime.getRuntime().availableProcessors());
	}
	
	/*
	 * 初始化boss线程
	 */
	private void initBoss(Executor boss,int count){
		//this.bosses = new 
		this.bosses=new NioServerBoss[count];
		for (int i = 0; i < bosses.length; i++) {
			bosses[i]=new NioServerBoss(boss,"boss thread"+(i+1),this);
		}
	}
	//初始化worker线程
	private void initWorker(Executor worker,int count){
		this.workers=new  NioServerWorker[count];
		for (int i = 0; i < workers.length; i++) {
			 workers[i]= new NioServerWorker(worker,"worker thread"+(i+1),this);
		}
	}
	//获取一个worker
	public Worker nextWorker(){
		return workers[Math.abs(wokerInteger.getAndIncrement()%workers.length)];
	}
	
	//获取一个boss
	public Boss nextBoss(){
		return bosses[Math.abs(bossInteger.getAndIncrement()%bosses.length)];
	}
}
